#!/bin/sh
###
 # @FilePath: /mqtt/RNDIS_Connect.sh
 # @Author: 张玉兰
 # @Date: 2025-04-22 15:15:34
 # @LastEditors: 张玉兰
 # @LastEditTime: 2025-04-22 16:37:52
 # @Description: 自动进行网络连接，并且每分钟检测一次连接是否正常
### 

# 检查网络连接的函数
check_network_connection() {
    ping -c 3 -W 1 8.8.8.8 > /dev/null 2>&1
    return $?
}

# 杀死udhcpc进程的函数
kill_udhcpc_process() {
    killall udhcpc
}


while true; do
    # 动态获取最大端口号的USB串口设备
    TTY_DEVICES=`ls /dev/ttyUSB* 2>/dev/null`
    if [ -z "$TTY_DEVICES" ]; then
        echo "未找到USB串口设备，将在 5 秒后重试..."
        sleep 5
        continue
    fi
    # echo "TTY_DEVICES:$TTY_DEVICES"

    MAX_TTY_DEVICE=""
    MAX_PORT_NUM=0
    for device in $TTY_DEVICES; do
        # echo "device:$device"

        # PORT_NUM=`echo "$device" | grep -oE '[0-9]+' | tail -n 1`
        PORT_NUM=`echo "$device" | grep -oE '[0-9]+' | awk 'END{print}'`

        # echo "PORT_NUM:$PORT_NUM"
        if [ "$PORT_NUM" -gt "$MAX_PORT_NUM" ]; then
            MAX_PORT_NUM=$PORT_NUM
            MAX_TTY_DEVICE=$device
        fi
    done
    TTY_DEVICE=$MAX_TTY_DEVICE

    # 可能的网卡名称列表
    POSSIBLE_IFACES="eth0 eth1 usb0 usb1"
    NETWORK_INTERFACE=""

    # 动态获取RNDIS网卡设备
    for iface in $POSSIBLE_IFACES; do
        if [ -d "/sys/class/net/$iface" ]; then
            if [ -d "/sys/class/net/$iface/device" ]; then
                uevent_file="/sys/class/net/$iface/device/uevent"
                if grep -q "DRIVER=rndis_host" "$uevent_file" 2>/dev/null; then
                    NETWORK_INTERFACE="$iface"
                    break
                fi
            fi
        fi
    done

    if [ -z "$NETWORK_INTERFACE" ]; then
        echo "未找到RNDIS网卡设备，将在 5 秒后重试..."
        sleep 5
        continue
    fi

    # 执行AT命令的函数
    send_at_command() {
        command=$1
        echo -e "$command\r\n" > "$TTY_DEVICE"
        # sleep 1
        echo "执行命令 $command"
 }

    # 关闭回显
    send_at_command "ATE"

    # 模组网络状态查询
    # 查询PDP上下文配置
    send_at_command "AT+CGDCONT?"

    # 查询驻网状态
    send_at_command "AT+COPS?"

    # AT拨号
    # 查询拨号状态
    send_at_command "AT+MDIALUP?"

    # 拨号命令
    send_at_command "AT+MDIALUP=1,1"

# 杀死可能存在的udhcpc进程
    kill_udhcpc_process

    # 获取IP
    echo "正在为 $NETWORK_INTERFACE 获取IP地址..."
    udhcpc -i "$NETWORK_INTERFACE"
    if [ $? -ne 0 ]; then
        echo "获取IP地址失败，将在 5 秒后重试..."
        sleep 5
        continue
    fi

    # 持续检查网络连接
    while true; do
        if check_network_connection; then
            echo "网络连接正常，将在 1 分钟后再次检查..."
            sleep 60
        else
            echo "网络连接中断，重新开始拨号流程..."
            break
        fi
    done
done